<template>
  <el-dialog :title="type + '字典类型'" v-model="dialogTableVisible" width="600px" append-to-body>
    <el-form :model="form" label-width="auto" ref="formRef" :rules="rules">
      <el-form-item label="字典名称" prop="dictName">
        <el-input v-model="form.dictName" placeholder="请输入字典名称" />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input v-model="form.dictType" placeholder="请输入字典类型" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="0">正常</el-radio>
          <el-radio label="1">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: right">
      <el-button type="primary" @click="submitForm(formRef)">确认</el-button>
      <el-button @click="dialogTableVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import { addDictTypeApi, editDictTypeApi } from "@/api/modules/dict";

const dialogTableVisible = ref(false);

const type = ref("新增");

const formRef = ref();

const form = reactive({
  dictName: "",
  dictType: "",
  status: "0"
});

const rules = reactive({
  dictName: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
  dictType: [{ required: true, message: "请输入字典类型", trigger: "blur" }]
});

const dictId = ref(null);

const openDialog = (data: any) => {
  dialogTableVisible.value = true;
  if (data) {
    type.value = "编辑";
    dictId.value = data.dictId;
    form.dictName = data.dictName;
    form.dictType = data.dictType;
    form.status = data.status;
  } else {
    type.value = "新增";
    dictId.value = null;
    form.dictName = "";
    form.dictType = "";
    form.status = "0";
  }
};

const emit = defineEmits(["update"]);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    if (valid) {
      if (type.value === "新增") {
        const res = await addDictTypeApi(form);
        if (res.code === 200) {
          emit("update");
          ElMessage.success("添加成功");
          dialogTableVisible.value = false;
        } else {
          ElMessage.error(res.msg);
        }
      } else {
        const res = await editDictTypeApi({ ...form, dictId: dictId.value! });
        if (res.code === 200) {
          emit("update");
          ElMessage.success("编辑成功");
          dialogTableVisible.value = false;
        } else {
          ElMessage.error(res.msg);
        }
      }
    }
  });
};

defineExpose({
  openDialog
});
</script>

<style scoped lang="scss"></style>
